//添加新分类（需选择父分类 + 输入名称）

import React, { useEffect, useRef } from 'react';
import { Form, Select, Input } from 'antd';
import PropTypes from 'prop-types';

const AddForm = ({ setForm, categorys, parentId }) => {
  const [form] = Form.useForm();
  const formRef = useRef(form); // 使用 useRef 缓存表单实例，避免组件重渲染时丢失

  useEffect(() => {
    setForm(formRef.current);
  }, [setForm]);

  return ( //vertical : 置表单布局为垂直排列（标签在上，输入框在下
    <Form form={form} layout="vertical">
      <Form.Item
        label="父分类"
        name="parentId"
        initialValue={parentId}
        rules={[{ required: true, message: '请选择父分类' }]}
      >
        <Select placeholder="请选择父分类">
          <Select.Option value="0">一级分类</Select.Option>
          {categorys.map((c) => (
            <Select.Option key={c._id} value={c._id}>
              {c.name}
            </Select.Option>
          ))}
        </Select>
      </Form.Item>

      <Form.Item
        label="分类名称"
        name="categoryName"
        rules={[{ required: true, message: '请输入分类名称' }]}
      >
        <Input placeholder="请输入分类名称" />
      </Form.Item>
    </Form>
  );
};


// 组件属性类型检查
AddForm.propTypes = {
  setForm: PropTypes.func.isRequired,
  categorys: PropTypes.array.isRequired,
  parentId: PropTypes.string.isRequired,
};

export default AddForm;